package it.antonio.ilpizze.te;

import java.io.IOException;
import java.io.InputStream;

public class StreamReader implements Reader{
	
	
	private boolean read = false;
	
	private int next;
	private int current;
	private java.io.Reader reader;
	private int position = -1;
	
	public StreamReader(InputStream stream)  {
		super();
		reader = new java.io.InputStreamReader(stream);
	}

	@Override
	public char current() {
		return (char) current;
	}

	@Override
	public int position() {
		return position;
	}

	@Override
	public void next() {
		current = next;
		read = false;
	}

	@Override
	public boolean hasNext() {
		try {
			if(!read) {
				next = reader.read();
				read = true;
			}
			return next != -1;
		
		} catch(IOException e){
			closeReader();
			throw new StreamReaderException(e);
		} 
	}

	@Override
	public void close() {
		try{
			reader.close();
		} catch(IOException e){
			closeReader();
			throw new StreamReaderException(e);
		} 
	}

	
	private void closeReader(){
		try {
			reader.close();
		} catch (IOException e) {
			throw new StreamReaderException(e);
		}
	}
	
	public static class StreamReaderException extends RuntimeException {

		private static final long serialVersionUID = 1L;

		public StreamReaderException(Throwable cause) {
			super(cause);
		}
		
	}
}
